package cn.myfirefly.core.mybatis;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import com.github.pagehelper.util.MetaObjectUtil;

import cn.myfirefly.utils.StrUtil;

@Intercepts(
        {
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        }
)
public class BjuiDataGridSqlInterceptor implements Interceptor {
	
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		try {
			BjuiDataGridFilter filter = BjuiDataGridSqlHelper.getFilter();
			if (filter != null) {
				String sql = getSqlByInvocation(invocation);
				if (StrUtil.isBlank(sql)) {
					return invocation.proceed();
				}
				
				StringBuffer buffer = new StringBuffer();
//				buffer.append("select * from (");
				buffer.append(sql);
//				buffer.append(") ");
//				buffer.append(filter.getTableName());
//				buffer.append(" where 1=1 ");
				buffer.append(filter.getFilterSql());
				
				resetSql2Invocation(invocation, buffer.toString(), filter);
			}
			return invocation.proceed();
		} finally {
			BjuiDataGridSqlHelper.clearFilter();
		}
	}

	@Override
	public Object plugin(Object obj) {
		return Plugin.wrap(obj, this);
	}

	@Override
	public void setProperties(Properties arg0) {
		// TODO Auto-generated method stub

	}

	/**
     * 获取sql语句
     * @param invocation
     * @return
     */
    private String getSqlByInvocation(Invocation invocation) {
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = ms.getBoundSql(parameterObject);
        return boundSql.getSql();
    }

    /**
     * 包装sql后，重置到invocation中
     * @param invocation
     * @param sql
     * @throws SQLException
     */
    private void resetSql2Invocation(Invocation invocation, String sql, BjuiDataGridFilter filter) throws SQLException {
        final Object[] args = invocation.getArgs();
        MappedStatement statement = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = statement.getBoundSql(parameterObject);
        BoundSql newBoundSql = new BoundSql(statement.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
        MappedStatement newStatement = newMappedStatement(statement, new BoundSqlSqlSource(newBoundSql));
//        MetaObject msObject =  MetaObject.forObject(newStatement, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
//        msObject.setValue("sqlSource.boundSql.sql", sql);
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }
        Map<String, Object> paramMap = filter.getParam();
        if (paramMap != null) {
        	List<ParameterMapping> newParameterMappings = null;
        	if (newBoundSql.getParameterMappings() != null) {
        		newParameterMappings = new ArrayList<ParameterMapping>(newBoundSql.getParameterMappings());
        	} else {
        		newParameterMappings = new ArrayList<ParameterMapping>();
			}
        	// FilterDto中参数的数量
        	int size = paramMap.size();
        	String key = null;
        	for (int i = 0; i < size; i++) {
        		key = String.valueOf(i+1);
        		newParameterMappings.add(new ParameterMapping.Builder(newStatement.getConfiguration(), key, paramMap.get(key).getClass()).build());
        	}
        	MetaObject metaObject = MetaObjectUtil.forObject(newBoundSql);
            metaObject.setValue("parameterMappings", newParameterMappings);
        }
        args[0] = newStatement;
    }
    
    private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder =
                new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
 
        return builder.build();
    }
 
    //定义一个内部辅助类，作用是包装sq
    class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;
        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }
        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }
}
